package com.roy.netty.sworddemo.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.EventExecutorGroup;

public class NettyServerChannelInitializer extends ChannelInitializer<SocketChannel> {

	private TransportSettings transportSettings;

	private EventExecutorGroup engineHandlerExecutor;
//	private ChannelHandler engineHandler;

	public NettyServerChannelInitializer(TransportSettings transportSettings) {
		this.transportSettings = transportSettings;

		int numThreads = transportSettings.getHandlerThreads();
		if (numThreads <= 0) {
			numThreads = Runtime.getRuntime().availableProcessors() * 4;
		}
		engineHandlerExecutor = new DefaultEventExecutorGroup(numThreads,
				new DefaultThreadFactory("handlerExecutor"));
		
//		this.engineHandler = ;
	}
	
	public EventExecutorGroup getEngineHandlerExecutor() {
		return this.engineHandlerExecutor;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		int preLength = 4;
		ChannelHandler lengthPrepender = new LengthFieldPrepender(4);
		// TODO Auto-generated method stub
		ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(
				transportSettings.getReaderIdleTimeSeconds(), 0, 0));
		ch.pipeline().addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(
				Integer.MAX_VALUE, 0, preLength, 0, preLength));

		ch.pipeline().addLast("lengthPrepender", lengthPrepender);
		ch.pipeline().addLast("bytesDecoder", new ByteArrayDecoder());
		ch.pipeline().addLast("bytesEncoder", new ByteArrayEncoder());
		// ch.pipeline().addLast("messageVersionCodec", messageVersionCodec);
		// ch.pipeline().addLast("messageFormatCodec", messageFormatCodec);
		// ch.pipeline().addLast(HandlerConstants.ENGINE_MESSAGE_CODEC,
		// engineMessageCodec);
		ch.pipeline().addLast(engineHandlerExecutor, "engineHandler",
				new ByteArrayEngineHandler());
	}

}
